package com.sian.anyun.web.services;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.atmosphere.cpr.AtmosphereResource;
import org.atmosphere.cpr.AtmosphereResourceFactory;
import org.springframework.stereotype.Service;

@Service
public class PresentService{
	Map<String, String> onlineUUID = new HashMap<String, String>();
	
	public boolean isRegister(String name)
	{
		return onlineUUID.containsKey(name);
	}

	public void register(String userId, String uuid)
	{
		onlineUUID.put(userId, uuid); 
	}
	
	public void remove(String uuid)
	{
		Iterator<String> iter = onlineUUID.keySet().iterator();
		while(iter.hasNext())
		{
			String userId = iter.next();
			if(onlineUUID.get(userId).equals(uuid))
			{
				onlineUUID.remove(userId);
				break;
			}
		}
	}
	
	public String getUUID(String userId)
	{
		return onlineUUID.get(userId);
	}
	
	public String getCurrentUserId(AtmosphereResource resource)
	{
		String uuid = resource.uuid();
		Iterator<String> iter = onlineUUID.keySet().iterator();
		while(iter.hasNext())
		{
			String userId = iter.next();
			if(onlineUUID.get(userId).equals(uuid))
			{
				return userId;
			}
		}
		
		throw new RuntimeException("Unknown user id");
	}
	
	public String[] getPresentUsers()
	{
		String[] users = new String[onlineUUID.keySet().size()];
		
		return onlineUUID.keySet().toArray(users);
	}
	
	public AtmosphereResource getAtmosphereResource(String userId)
	{
		String uuid = getUUID(userId);
		
		if(null != uuid)
		{
			return AtmosphereResourceFactory.getDefault().find(uuid);
		}
		return null;
	}
}
